<?php
$GLOBALS['CACHES_EXPIRE'] = 2 * 60 * 60; //2 hours
$GLOBALS['CACHES_DIR'] = "./cache";


class filehandle {

	var $cache_dir;

	function filehandle() {
		$this->cache_dir = $GLOBALS['CACHES_DIR'];
	}

	//
	function is_able_write() {

		if (!file_exists($this->cache_dir)) @mkdir($this->cache_dir,0777);

		if (is_writable($this->cache_dir))
			return true;

		die("<span class='error'>NOTE: Please make cache directoy writable</span>");

		return false;
	}
	
	//Garbage Collector
	function gc() {

		$timenow = time();
		$dir = $this->cache_dir;
		if (!file_exists($dir)) mkdir($dir, 0755);

		$this->is_able_write();

		if ($handle = opendir($dir)) {

			while (false !== ($file = readdir($handle))) { 

				if ($file != "." && $file != "..") {
					$src = $dir.'/'.$file;
					$last_modified = filemtime($src);
					if ($timenow - $last_modified >= $GLOBALS['CACHES_EXPIRE'] ) {
						@unlink($src);
					}
				} 
			}
			closedir($handle); 
		} else { 
			echo(' UNABLE to read cache<br>'."\n");
		}
	}
	
	//
	function read_data($fxid) {

		if(empty($fxid)) return '';

		$dir = $this->cache_dir.'/'.$fxid;

		if(!file_exists($dir)) {
			$handle = @fopen($dir, 'w');
			@fwrite($handle, '');
			@fclose($handle);
		}

		$contents = file_get_contents($dir);
		return unserialize($contents);
	}
	
	//
	function write_data($fxid, $data) {
		
		$this->gc();
		$dir = $this->cache_dir.'/'.$fxid;
		$contents = serialize($data);
		
		//$put = file_put_contents($dir, $contents);
		$handle = @fopen($dir, 'w');
		@fwrite($handle, $contents);
		@fclose($handle);
	}

	//
	function is_expired($fxid) {
		
		$this->gc();
		$dir = $this->cache_dir.'/'.$fxid;
			
		if(!file_exists($dir)) {
			return true;
		}
		return false;
	}


}
?>